package cn.android666.net.util.download.apkdownload

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresPermission
import androidx.core.content.FileProvider
import timber.log.Timber
import java.io.File

object ApkUtil {

    /**
     * 安装apk，需要权限：android.permission.REQUEST_INSTALL_PACKAGES
     * @param apkPath 要安装的apk文件的路径
     */
    @SuppressLint("InlinedApi")
    @RequiresPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES)
    fun install(context: Context, apkPath: String) {
        try {
            val file = File(apkPath)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val apkUri: Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //android7.0或以上版本
                // 参数2 = android:authorities="应用包名.fileProvider"属性值和清单配置文件中保持一致
                val authorities = context.packageName + ".NetUtilFileProvider"
                apkUri = FileProvider.getUriForFile(context, authorities, file)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) //添加这一句表示对目标应用临时授权该Uri所代表的文件
            } else {
                apkUri = Uri.fromFile(file)
            }
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
            context.startActivity(intent)
        } catch (e: Exception) {
            Timber.w(e, "请求安装apk时出现异常")
        }
    }

}